{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Getting Started with AmpliGraph\n",
    "\n",
    "In this tutorial we will demonstrate how to use the AmpliGraph library. \n",
    "\n",
    "Things we will cover:\n",
    "\n",
    "1. Exploration of a graph dataset\n",
    "2. Splitting graph datasets into train and test sets\n",
    "3. Training and Evaluation a Model\n",
    "4. Saving and restoring a model\n",
    "5. Predicting New Links\n",
    "6. Visualizing embeddings using Tensorboard\n",
    "\n",
    "\n",
    "\n",
    "## Requirements\n",
    "\n",
    "A Python environment with the AmpliGraph library installed. Please follow [the install guide](http://docs.ampligraph.org/en/latest/install.html).\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Some sanity check:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2.0-dev'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import ampligraph\n",
    "\n",
    "ampligraph.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 1. Dataset Exploration"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First things first! Lets import the required libraries and retrieve some data.\n",
    "\n",
    "In this tutorial we're going to use the [**Game of Thrones knowledge Graph**](https://ampligraph.s3-eu-west-1.amazonaws.com/datasets/GoT.csv). Please note: this isn't the *greatest* dataset for demonstrating the power of knowledge graph embeddings, but is small, intuitive and should be familiar to most users. \n",
    "\n",
    "We downloaded the [neo4j graph published here](https://github.com/neo4j-examples/game-of-thrones). Such dataset has been generated using [these APIs](https://anapioficeandfire.com/)  which expose in a machine-readable fashion the content of open free sources such as A [Wiki of Ice and Fire](http://awoiaf.westeros.org/). We discarded all properties and saved all the directed, labeled relations in a plaintext file. Each relation (i.e. a triple) is in the form: \n",
    "\n",
    "    <subject, predicate, object>\n",
    "\n",
    "The schema of the graph looks like this (image from [neo4j-examples/game-of-thrones](https://github.com/neo4j-examples/game-of-thrones)):\n",
    "\n",
    "![](img/got-graphql-schema.jpg)\n",
    "\n",
    "Run the following cell to pull down the dataset and load it in memory with AmpliGraph [`load_from_csv()`](http://docs.ampligraph.org/en/1.0.3/generated/ampligraph.datasets.load_from_csv.html#ampligraph.datasets.load_from_csv) utility function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([['Smithyton', 'SEAT_OF', 'House Shermer of Smithyton'],\n",
       "       ['House Mormont of Bear Island', 'LED_BY', 'Maege Mormont'],\n",
       "       ['Margaery Tyrell', 'SPOUSE', 'Joffrey Baratheon'],\n",
       "       ['Maron Nymeros Martell', 'ALLIED_WITH',\n",
       "        'House Nymeros Martell of Sunspear'],\n",
       "       ['House Gargalen of Salt Shore', 'IN_REGION', 'Dorne']],\n",
       "      dtype=object)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import requests\n",
    "from ampligraph.datasets import load_from_csv\n",
    "\n",
    "url = 'https://ampligraph.s3-eu-west-1.amazonaws.com/datasets/GoT.csv'\n",
    "open('GoT.csv', 'wb').write(requests.get(url).content)\n",
    "X = load_from_csv('.', 'GoT.csv', sep=',')\n",
    "X[:5, ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's list the subject and object entities found in the dataset..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['Abelar Hightower', 'Acorn Hall', 'Addam Frey', ..., 'the Antlers',\n",
       "       'the Paps', 'unnamed tower'], dtype=object)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "entities = np.unique(np.concatenate([X[:, 0], X[:, 2]]))\n",
    "entities"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "... and all of the relationships that link them. Remember, these relationships only link *some* of the entities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['ALLIED_WITH', 'BRANCH_OF', 'FOUNDED_BY', 'HEIR_TO', 'IN_REGION',\n",
       "       'LED_BY', 'PARENT_OF', 'SEAT_OF', 'SPOUSE', 'SWORN_TO'],\n",
       "      dtype=object)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "relations = np.unique(X[:, 1])\n",
    "relations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 2. Defining Train and Test Datasets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As is typical in machine learning, we need to split our dataset into training and test (and sometimes validation) datasets. \n",
    "\n",
    "When dealing with Knowledge Graphs, there is a major difference with the standard method of randomly sampling N points to make up our test set. Indeed, each of our data points are two entities linked by some relationship, and we need to ensure that all entities and relationships that are represented in the test set are present in the training set in at least one triple. \n",
    "\n",
    "To accomplish this, AmpliGraph provides the [`train_test_split_no_unseen`](https://docs.ampligraph.org/en/latest/generated/ampligraph.evaluation.train_test_split_no_unseen.html#train-test-split-no-unseen) function.  \n",
    "\n",
    "As an example, we will create a small test size that includes only 100 triples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ampligraph.evaluation import train_test_split_no_unseen \n",
    "\n",
    "X_train, X_test = train_test_split_no_unseen(X, test_size=100) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our data is now split into train/test sets. If we needed to further obtain a validation dataset, we can just repeat the same procedure on the test set (and adjusting the split percentages). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train set size:  (3075, 3)\n",
      "Test set size:  (100, 3)\n"
     ]
    }
   ],
   "source": [
    "print('Train set size: ', X_train.shape)\n",
    "print('Test set size: ', X_test.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 3. Training a Model\n",
    "\n",
    "AmpliGraph 2 has a unique class for defining [several](https://docs.ampligraph.org/en/latest/ampligraph.latent_features.html#knowledge-graph-embedding-models) Knoweldge Graph Embedding models (TransE, ComplEx, DistMult, HolE), it sufficies to specify the different scoring type. Together with that, at initialization time, we also need to define some parameters:\n",
    "- **`k`** : the dimensionality of the embedding space;\n",
    "- **`eta`** ($\\eta$) : the number of negatives (i.e., false triples) that must be generated at training runtime for each positive (i.e., true triple).\n",
    "\n",
    "To begin with we are going to use the [ComplEx](https://docs.ampligraph.org/en/latest/generated/ampligraph.latent_features.ComplEx.html#ampligraph.latent_features.ComplEx) model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ampligraph.latent_features import ScoringBasedEmbeddingModel\n",
    "model = ScoringBasedEmbeddingModel(k=150,\n",
    "                                   eta=5,\n",
    "                                   scoring_type='ComplEx',\n",
    "                                   seed=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Right after defining the model, it is time to compile the model, specifying:\n",
    "\n",
    "- **`optimizer`** : we will use the Adam optimizer, with a learning rate of 1e-3, but AmpliGraph 2 supports any _tf.keras.optimizers_;\n",
    "- **`loss`** : we will consider the pairwise loss, with a margin of 0.5 set via the *loss_params* kwarg. However, many other loss functions are supported, and custom losses can be defined by the user;\n",
    "- **`regularizer`** : we will use the $L_p$ regularization with $p=2$, i.e. L2 regularization. The regularization parameter $\\lambda$ = 1e-5 is set via the *regularizer_params* kwarg. Also in this case, _tf.keras.regularizers_ are supported.\n",
    "- **`initializer`** : we will use the Glorot Uniform initialization, but the _tf.keras.initializers_ are supported.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ampligraph.latent_features.loss_functions import get as get_loss\n",
    "from ampligraph.latent_features.regularizers import get as get_regularizer\n",
    "from tensorflow.keras.optimizers import Adam\n",
    "\n",
    "optimizer = Adam(learning_rate=1e-3)\n",
    "loss = get_loss('pairwise', {'margin': 0.5})\n",
    "regularizer = get_regularizer('LP', {'p': 2, 'lambda': 1e-5})\n",
    "\n",
    "model.compile(loss=loss,\n",
    "              optimizer='adam',\n",
    "              entity_relation_regularizer=regularizer,\n",
    "              entity_relation_initializer='glorot_uniform')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "AmpliGraph follows the _tensorflow.keras_ style APIs, allowing, after compiling the model, to perform the main operations of the model with the **`fit`**, **`predict`**, and **`evaluate`** methods. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Fitting the Model\n",
    "\n",
    "Once you run the next cell the model will start training. \n",
    "\n",
    "On a modern laptop this should take ~3 minutes (although your mileage may vary, especially if you have changed any of the hyper-parameters above)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-02-08 23:06:27.469961: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/200\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-02-08 23:06:28.230759: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2/2 [==============================] - 1s 668ms/step - loss: 7687.5562\n",
      "Epoch 2/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7683.3623\n",
      "Epoch 3/200\n",
      "2/2 [==============================] - 0s 48ms/step - loss: 7679.1382\n",
      "Epoch 4/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7674.8130\n",
      "Epoch 5/200\n",
      "2/2 [==============================] - 0s 48ms/step - loss: 7670.5405\n",
      "Epoch 6/200\n",
      "2/2 [==============================] - 0s 44ms/step - loss: 7666.1504\n",
      "Epoch 7/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7661.6445\n",
      "Epoch 8/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7657.1768\n",
      "Epoch 9/200\n",
      "2/2 [==============================] - 0s 46ms/step - loss: 7652.6147\n",
      "Epoch 10/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7647.9399\n",
      "Epoch 11/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7643.0947\n",
      "Epoch 12/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7638.1758\n",
      "Epoch 13/200\n",
      "2/2 [==============================] - 0s 48ms/step - loss: 7633.1064\n",
      "Epoch 14/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7627.8647\n",
      "Epoch 15/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7622.4819\n",
      "Epoch 16/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 7616.9292\n",
      "Epoch 17/200\n",
      "2/2 [==============================] - 0s 44ms/step - loss: 7611.2173\n",
      "Epoch 18/200\n",
      "2/2 [==============================] - 0s 44ms/step - loss: 7605.2847\n",
      "Epoch 19/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7599.1416\n",
      "Epoch 20/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7592.7905\n",
      "Epoch 21/200\n",
      "2/2 [==============================] - 0s 46ms/step - loss: 7586.2324\n",
      "Epoch 22/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 7579.4341\n",
      "Epoch 23/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7572.4092\n",
      "Epoch 24/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7565.1226\n",
      "Epoch 25/200\n",
      "2/2 [==============================] - 0s 47ms/step - loss: 7557.5513\n",
      "Epoch 26/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7549.6802\n",
      "Epoch 27/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7541.4810\n",
      "Epoch 28/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7533.0098\n",
      "Epoch 29/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7524.2012\n",
      "Epoch 30/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 7515.0493\n",
      "Epoch 31/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7505.5547\n",
      "Epoch 32/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7495.6831\n",
      "Epoch 33/200\n",
      "2/2 [==============================] - 0s 44ms/step - loss: 7485.4292\n",
      "Epoch 34/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 7474.8052\n",
      "Epoch 35/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7463.7358\n",
      "Epoch 36/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7452.2334\n",
      "Epoch 37/200\n",
      "2/2 [==============================] - 0s 47ms/step - loss: 7440.3193\n",
      "Epoch 38/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7427.9673\n",
      "Epoch 39/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7415.1470\n",
      "Epoch 40/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7401.8252\n",
      "Epoch 41/200\n",
      "2/2 [==============================] - 0s 47ms/step - loss: 7388.0103\n",
      "Epoch 42/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 7373.6465\n",
      "Epoch 43/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7358.7339\n",
      "Epoch 44/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7343.2524\n",
      "Epoch 45/200\n",
      "2/2 [==============================] - 0s 46ms/step - loss: 7327.1968\n",
      "Epoch 46/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 7310.5498\n",
      "Epoch 47/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7293.2598\n",
      "Epoch 48/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7275.4258\n",
      "Epoch 49/200\n",
      "2/2 [==============================] - 0s 47ms/step - loss: 7256.8550\n",
      "Epoch 50/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7237.6069\n",
      "Epoch 51/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7217.6772\n",
      "Epoch 52/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7197.0957\n",
      "Epoch 53/200\n",
      "2/2 [==============================] - 0s 45ms/step - loss: 7175.7148\n",
      "Epoch 54/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7153.5884\n",
      "Epoch 55/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7130.6948\n",
      "Epoch 56/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7106.9736\n",
      "Epoch 57/200\n",
      "2/2 [==============================] - 0s 46ms/step - loss: 7082.3877\n",
      "Epoch 58/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 7056.9937\n",
      "Epoch 59/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 7030.7690\n",
      "Epoch 60/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 7003.6494\n",
      "Epoch 61/200\n",
      "2/2 [==============================] - 0s 48ms/step - loss: 6975.6445\n",
      "Epoch 62/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 6946.6948\n",
      "Epoch 63/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6916.8398\n",
      "Epoch 64/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6885.9805\n",
      "Epoch 65/200\n",
      "2/2 [==============================] - 0s 47ms/step - loss: 6854.2222\n",
      "Epoch 66/200\n",
      "2/2 [==============================] - 0s 43ms/step - loss: 6821.4287\n",
      "Epoch 67/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6787.4209\n",
      "Epoch 68/200\n",
      "2/2 [==============================] - 0s 41ms/step - loss: 6752.3765\n",
      "Epoch 69/200\n",
      "2/2 [==============================] - 0s 46ms/step - loss: 6716.2451\n",
      "Epoch 70/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 6678.9810\n",
      "Epoch 71/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6640.5068\n",
      "Epoch 72/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6600.8901\n",
      "Epoch 73/200\n",
      "2/2 [==============================] - 0s 48ms/step - loss: 6560.0127\n",
      "Epoch 74/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 6517.9282\n",
      "Epoch 75/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6474.5786\n",
      "Epoch 76/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6429.9829\n",
      "Epoch 77/200\n",
      "2/2 [==============================] - 0s 44ms/step - loss: 6384.1543\n",
      "Epoch 78/200\n",
      "2/2 [==============================] - 0s 42ms/step - loss: 6337.0464\n",
      "Epoch 79/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 6288.6187\n",
      "Epoch 80/200\n",
      "2/2 [==============================] - 0s 39ms/step - loss: 6238.8779\n",
      "Epoch 81/200\n",
      "2/2 [==============================] - 0s 46ms/step - loss: 6187.8340\n",
      "Epoch 82/200\n",
      "2/2 [==============================] - 0s 40ms/step - loss: 6135.7783\n",
      "Epoch 83/200\n",
      "2/2 [==============================] - 0s 37ms/step - loss: 6082.6733\n",
      "Epoch 84/200\n",
      "2/2 [==============================] - 0s 36ms/step - loss: 6028.7832\n",
      "Epoch 85/200\n",
      "2/2 [==============================] - 0s 38ms/step - loss: 5974.1294\n",
      "Epoch 86/200\n",
      "2/2 [==============================] - 0s 36ms/step - loss: 5919.1519\n",
      "Epoch 87/200\n",
      "2/2 [==============================] - 0s 31ms/step - loss: 5863.7749\n",
      "Epoch 88/200\n",
      "2/2 [==============================] - 0s 31ms/step - loss: 5808.1211\n",
      "Epoch 89/200\n",
      "2/2 [==============================] - 0s 34ms/step - loss: 5752.3843\n",
      "Epoch 90/200\n",
      "2/2 [==============================] - 0s 31ms/step - loss: 5696.8433\n",
      "Epoch 91/200\n",
      "2/2 [==============================] - 0s 29ms/step - loss: 5641.3433\n",
      "Epoch 92/200\n",
      "2/2 [==============================] - 0s 27ms/step - loss: 5586.2896\n",
      "Epoch 93/200\n",
      "2/2 [==============================] - 0s 30ms/step - loss: 5531.6914\n",
      "Epoch 94/200\n",
      "2/2 [==============================] - 0s 26ms/step - loss: 5477.6558\n",
      "Epoch 95/200\n",
      "2/2 [==============================] - 0s 25ms/step - loss: 5424.2500\n",
      "Epoch 96/200\n",
      "2/2 [==============================] - 0s 24ms/step - loss: 5371.4414\n",
      "Epoch 97/200\n",
      "2/2 [==============================] - 0s 26ms/step - loss: 5319.4209\n",
      "Epoch 98/200\n",
      "2/2 [==============================] - 0s 25ms/step - loss: 5268.1343\n",
      "Epoch 99/200\n",
      "2/2 [==============================] - 0s 22ms/step - loss: 5217.6074\n",
      "Epoch 100/200\n",
      "2/2 [==============================] - 0s 22ms/step - loss: 5167.8394\n",
      "Epoch 101/200\n",
      "2/2 [==============================] - 0s 22ms/step - loss: 5118.7812\n",
      "Epoch 102/200\n",
      "2/2 [==============================] - 0s 23ms/step - loss: 5070.6216\n",
      "Epoch 103/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 5023.2554\n",
      "Epoch 104/200\n",
      "2/2 [==============================] - 0s 22ms/step - loss: 4976.6865\n",
      "Epoch 105/200\n",
      "2/2 [==============================] - 0s 23ms/step - loss: 4930.8843\n",
      "Epoch 106/200\n",
      "2/2 [==============================] - 0s 22ms/step - loss: 4885.9780\n",
      "Epoch 107/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 4841.7085\n",
      "Epoch 108/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4798.2017\n",
      "Epoch 109/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 4755.4863\n",
      "Epoch 110/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 4713.4092\n",
      "Epoch 111/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4672.1030\n",
      "Epoch 112/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4631.4775\n",
      "Epoch 113/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 4591.5752\n",
      "Epoch 114/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4552.3101\n",
      "Epoch 115/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4513.6792\n",
      "Epoch 116/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4475.6802\n",
      "Epoch 117/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4438.3237\n",
      "Epoch 118/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4401.5659\n",
      "Epoch 119/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4365.4551\n",
      "Epoch 120/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4329.9443\n",
      "Epoch 121/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4295.0410\n",
      "Epoch 122/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4260.6831\n",
      "Epoch 123/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4226.8403\n",
      "Epoch 124/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4193.5107\n",
      "Epoch 125/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4160.7246\n",
      "Epoch 126/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4128.4478\n",
      "Epoch 127/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4096.6489\n",
      "Epoch 128/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4065.3191\n",
      "Epoch 129/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 4034.4797\n",
      "Epoch 130/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 4004.1243\n",
      "Epoch 131/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3974.1709\n",
      "Epoch 132/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3944.7107\n",
      "Epoch 133/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3915.5930\n",
      "Epoch 134/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 3886.9021\n",
      "Epoch 135/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3858.7039\n",
      "Epoch 136/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3830.8809\n",
      "Epoch 137/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3803.4395\n",
      "Epoch 138/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3776.4390\n",
      "Epoch 139/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3749.7639\n",
      "Epoch 140/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3723.4912\n",
      "Epoch 141/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3697.5691\n",
      "Epoch 142/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3672.0378\n",
      "Epoch 143/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3646.8630\n",
      "Epoch 144/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3621.9890\n",
      "Epoch 145/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3597.5039\n",
      "Epoch 146/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3573.3049\n",
      "Epoch 147/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3549.4644\n",
      "Epoch 148/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3525.8699\n",
      "Epoch 149/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 3502.6682\n",
      "Epoch 150/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3479.8208\n",
      "Epoch 151/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3457.2893\n",
      "Epoch 152/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 3435.0530\n",
      "Epoch 153/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3413.0737\n",
      "Epoch 154/200\n",
      "2/2 [==============================] - 0s 23ms/step - loss: 3391.3215\n",
      "Epoch 155/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 3369.8508\n",
      "Epoch 156/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3348.6760\n",
      "Epoch 157/200\n",
      "2/2 [==============================] - 0s 23ms/step - loss: 3327.7073\n",
      "Epoch 158/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3307.0623\n",
      "Epoch 159/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3286.6704\n",
      "Epoch 160/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 3266.4805\n",
      "Epoch 161/200\n",
      "2/2 [==============================] - 0s 22ms/step - loss: 3246.6299\n",
      "Epoch 162/200\n",
      "2/2 [==============================] - 0s 21ms/step - loss: 3227.0281\n",
      "Epoch 163/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3207.6719\n",
      "Epoch 164/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3188.4419\n",
      "Epoch 165/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3169.4727\n",
      "Epoch 166/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3150.6953\n",
      "Epoch 167/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3132.2092\n",
      "Epoch 168/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3113.9177\n",
      "Epoch 169/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3095.8491\n",
      "Epoch 170/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3077.9492\n",
      "Epoch 171/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3060.3206\n",
      "Epoch 172/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3042.8682\n",
      "Epoch 173/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 3025.6821\n",
      "Epoch 174/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 3008.5740\n",
      "Epoch 175/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2991.7039\n",
      "Epoch 176/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2975.0493\n",
      "Epoch 177/200\n",
      "2/2 [==============================] - 0s 18ms/step - loss: 2958.5591\n",
      "Epoch 178/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2942.2769\n",
      "Epoch 179/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2926.1487\n",
      "Epoch 180/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2910.1887\n",
      "Epoch 181/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2894.3938\n",
      "Epoch 182/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2878.7822\n",
      "Epoch 183/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2863.3167\n",
      "Epoch 184/200\n",
      "2/2 [==============================] - 0s 18ms/step - loss: 2848.0630\n",
      "Epoch 185/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2832.9565\n",
      "Epoch 186/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2817.9868\n",
      "Epoch 187/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2803.1804\n",
      "Epoch 188/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2788.5645\n",
      "Epoch 189/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2774.0742\n",
      "Epoch 190/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2759.7258\n",
      "Epoch 191/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2745.5208\n",
      "Epoch 192/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2731.5134\n",
      "Epoch 193/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2717.6428\n",
      "Epoch 194/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2703.9246\n",
      "Epoch 195/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2690.2976\n",
      "Epoch 196/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2676.8450\n",
      "Epoch 197/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2663.5295\n",
      "Epoch 198/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2650.3706\n",
      "Epoch 199/200\n",
      "2/2 [==============================] - 0s 19ms/step - loss: 2637.3049\n",
      "Epoch 200/200\n",
      "2/2 [==============================] - 0s 20ms/step - loss: 2624.3518\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<tensorflow.python.keras.callbacks.History at 0x15fd63520>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit(X_train,\n",
    "          batch_size=5000,\n",
    "          epochs=200,\n",
    "          verbose=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Predicting with the Model\n",
    "After having trained the model, we can use it to predict the score for any unseen triple given that its subject, relation and object were present in the training set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0.09504332], dtype=float32)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict(np.array([['Leyton Hightower', 'ALLIED_WITH', 'House Ryswell of the Rills']]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Evaluating\n",
    "Now it is time to evaluate our model on the test set to see how well it's performing. \n",
    "\n",
    "For this we are going to use the `evaluate` method, which takes as arguments:\n",
    "\n",
    "- **`X_test`** : the data to evaluate on. We're going to use our test set to evaluate.\n",
    "- **`use_filter`** : whether to filter out the false negatives generated by the corruption strategy. If a dictionary is passed, the values of it are used as elements to filter.\n",
    "- **`corrupt_side`** : specifies whether to corrupt subj and obj separately or to corrupt both during evaluation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-02-09 15:57:55.492610: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5/5 [==============================] - 1s 297ms/step\n"
     ]
    }
   ],
   "source": [
    "positives_filter = {'test' : np.concatenate([X_train, X_test])}\n",
    "ranks = model.evaluate(X_test, \n",
    "                       use_filter=positives_filter,   # Corruption strategy filter defined above \n",
    "                       corrupt_side='s,o', # corrupt subj and obj separately while evaluating\n",
    "                       verbose=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ***ranks*** returned by the evaluate_performance function indicate the rank at which the test set triple was found when performing link prediction using the model. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Metrics\n",
    "Let's compute some evaluate metrics and print them out.\n",
    "\n",
    "We're going to use the *mrr_score* (mean reciprocal rank) and *hits_at_n_score* functions. \n",
    "\n",
    "- ***mrr_score***:  The function computes the mean of the reciprocal of elements of a vector of rankings ranks.\n",
    "- ***hits_at_n_score***: The function computes how many elements of a vector of rankings ranks make it to the top n positions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MRR: 0.26\n",
      "Hits@10: 0.37\n",
      "Hits@3: 0.28\n",
      "Hits@1: 0.20\n"
     ]
    }
   ],
   "source": [
    "from ampligraph.evaluation import mr_score, mrr_score, hits_at_n_score\n",
    "\n",
    "mrr = mrr_score(ranks)\n",
    "print(\"MRR: %.2f\" % (mrr))\n",
    "\n",
    "hits_10 = hits_at_n_score(ranks, n=10)\n",
    "print(\"Hits@10: %.2f\" % (hits_10))\n",
    "hits_3 = hits_at_n_score(ranks, n=3)\n",
    "print(\"Hits@3: %.2f\" % (hits_3))\n",
    "hits_1 = hits_at_n_score(ranks, n=1)\n",
    "print(\"Hits@1: %.2f\" % (hits_1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, how do we interpret those numbers? \n",
    "\n",
    "[Hits@N](http://docs.ampligraph.org/en/1.0.3/generated/ampligraph.evaluation.hits_at_n_score.html#ampligraph.evaluation.hits_at_n_score) indicates how many times in average a true triple was ranked in the top-N. Therefore, on average, we guessed the correct subject or object 53% of the time when considering the top-3 better ranked triples. The choice of which N makes more sense depends on the application.\n",
    "\n",
    "The [Mean Reciprocal Rank (MRR)](http://docs.ampligraph.org/en/latest/generated/ampligraph.evaluation.mrr_score.html) is another popular metrics to assess the predictive power of a model."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 4.  Saving and Restoring a Model\n",
    "\n",
    "Before we go any further, let's save the best model found so that we can restore it in future."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ampligraph.utils import save_model, restore_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING - Found untraced functions such as _get_ranks while saving (showing 1 of 1). These functions will not be directly callable after loading.\n"
     ]
    }
   ],
   "source": [
    "save_model(model, './best_model.pkl')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This will save the model in the ampligraph_tutorial directory as `best_model.pkl`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can then delete the model..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "del model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ".|.. and then restore it from disk! Ta-da! "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Saved model does not include a db file. Skipping.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-02-09 13:15:34.968306: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n",
      "2023-02-09 13:15:34.990256: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n"
     ]
    }
   ],
   "source": [
    "model = restore_model('./best_model.pkl')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And let's just double check that the model we restored has been fit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The model is fit!\n"
     ]
    }
   ],
   "source": [
    "if model.is_fitted:\n",
    "    print('The model is fit!')\n",
    "else:\n",
    "    print('The model is not fit! Did you skip a step?')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 5. Predicting New Links\n",
    "\n",
    "Link prediction allows us to infer missing links in a graph. This has many real-world use cases, such as predicting connections between people in a social network, interactions between proteins in a biological network, and music recommendation based on prior user taste. \n",
    "\n",
    "In our case, we're going to see which of the following candidate statements (that we made up) are more likely to be true:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_unseen = np.array([\n",
    "    ['Jorah Mormont', 'SPOUSE', 'Daenerys Targaryen'],\n",
    "    ['Tyrion Lannister', 'SPOUSE', 'Missandei'],\n",
    "    [\"King's Landing\", 'SEAT_OF', 'House Lannister of Casterly Rock'],\n",
    "    ['Sansa Stark', 'SPOUSE', 'Petyr Baelish'],\n",
    "    ['Daenerys Targaryen', 'SPOUSE', 'Jon Snow'],\n",
    "    ['Daenerys Targaryen', 'SPOUSE', 'Craster'],\n",
    "    ['House Stark of Winterfell', 'IN_REGION', 'The North'],\n",
    "    ['House Stark of Winterfell', 'IN_REGION', 'Dorne'],\n",
    "    ['House Tyrell of Highgarden', 'IN_REGION', 'Beyond the Wall'],\n",
    "    ['Brandon Stark', 'ALLIED_WITH', 'House Stark of Winterfell'],\n",
    "    ['Brandon Stark', 'ALLIED_WITH', 'House Lannister of Casterly Rock'],    \n",
    "    ['Rhaegar Targaryen', 'PARENT_OF', 'Jon Snow'],\n",
    "    ['House Hutcheson', 'SWORN_TO', 'House Tyrell of Highgarden'],\n",
    "    ['Daenerys Targaryen', 'ALLIED_WITH', 'House Stark of Winterfell'],\n",
    "    ['Daenerys Targaryen', 'ALLIED_WITH', 'House Lannister of Casterly Rock'],\n",
    "    ['Jaime Lannister', 'PARENT_OF', 'Myrcella Baratheon'],\n",
    "    ['Robert I Baratheon', 'PARENT_OF', 'Myrcella Baratheon'],\n",
    "    ['Cersei Lannister', 'PARENT_OF', 'Myrcella Baratheon'],\n",
    "    ['Cersei Lannister', 'PARENT_OF', 'Brandon Stark'],\n",
    "    [\"Tywin Lannister\", 'PARENT_OF', 'Jaime Lannister'],\n",
    "    [\"Missandei\", 'SPOUSE', 'Grey Worm'],\n",
    "    [\"Brienne of Tarth\", 'SPOUSE', 'Jaime Lannister']\n",
    "])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "positives_filter['test'] = np.vstack((positives_filter['test'], X_unseen))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-02-09 13:19:35.033726: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n",
      "2023-02-09 13:19:35.252684: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2/2 [==============================] - 1s 401ms/step\n"
     ]
    }
   ],
   "source": [
    "ranks_unseen = model.evaluate(X_unseen,\n",
    "                              use_filter=positives_filter,   # Corruption strategy filter defined above \n",
    "                              corrupt_side = 's+o',\n",
    "                              verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-02-09 13:19:40.424379: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.\n"
     ]
    }
   ],
   "source": [
    "scores = model.predict(X_unseen)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We transform the scores (real numbers) into probabilities (bound between 0 and 1) using the expit transform.\n",
    "\n",
    "Note that the probabilities are not calibrated in any sense. \n",
    "\n",
    "Advanced note: To calibrate the probabilities, one may use a procedure such as [Platt scaling](https://en.wikipedia.org/wiki/Platt_scaling) or [Isotonic regression](https://en.wikipedia.org/wiki/Isotonic_regression). The challenge is to define what is a true triple and what is a false one, as the calibration of the probability of a triple being true depends on the base rate of positives and negatives."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [],
   "source": [
    "from scipy.special import expit\n",
    "probs = expit(scores)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>statement</th>\n",
       "      <th>rank</th>\n",
       "      <th>score</th>\n",
       "      <th>prob</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>House Hutcheson SWORN_TO House Tyrell of Highg...</td>\n",
       "      <td>[-1]</td>\n",
       "      <td>0.830148</td>\n",
       "      <td>0.696386</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Brandon Stark ALLIED_WITH House Stark of Winte...</td>\n",
       "      <td>[-1]</td>\n",
       "      <td>0.630217</td>\n",
       "      <td>0.652539</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>House Stark of Winterfell IN_REGION The North</td>\n",
       "      <td>[7]</td>\n",
       "      <td>0.235329</td>\n",
       "      <td>0.558562</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>House Tyrell of Highgarden IN_REGION Beyond th...</td>\n",
       "      <td>[206]</td>\n",
       "      <td>0.110351</td>\n",
       "      <td>0.527560</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Sansa Stark SPOUSE Petyr Baelish</td>\n",
       "      <td>[499]</td>\n",
       "      <td>0.084068</td>\n",
       "      <td>0.521005</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>House Stark of Winterfell IN_REGION Dorne</td>\n",
       "      <td>[637]</td>\n",
       "      <td>0.079129</td>\n",
       "      <td>0.519772</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>Daenerys Targaryen ALLIED_WITH House Stark of ...</td>\n",
       "      <td>[688]</td>\n",
       "      <td>0.058003</td>\n",
       "      <td>0.514497</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>Jaime Lannister PARENT_OF Myrcella Baratheon</td>\n",
       "      <td>[674]</td>\n",
       "      <td>0.055809</td>\n",
       "      <td>0.513949</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>20</th>\n",
       "      <td>Missandei SPOUSE Grey Worm</td>\n",
       "      <td>[650]</td>\n",
       "      <td>0.046343</td>\n",
       "      <td>0.511584</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>King's Landing SEAT_OF House Lannister of Cast...</td>\n",
       "      <td>[1066]</td>\n",
       "      <td>0.032168</td>\n",
       "      <td>0.508041</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Jorah Mormont SPOUSE Daenerys Targaryen</td>\n",
       "      <td>[1645]</td>\n",
       "      <td>0.021946</td>\n",
       "      <td>0.505486</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>Rhaegar Targaryen PARENT_OF Jon Snow</td>\n",
       "      <td>[1728]</td>\n",
       "      <td>0.008681</td>\n",
       "      <td>0.502170</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>17</th>\n",
       "      <td>Cersei Lannister PARENT_OF Myrcella Baratheon</td>\n",
       "      <td>[1978]</td>\n",
       "      <td>0.006947</td>\n",
       "      <td>0.501737</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>21</th>\n",
       "      <td>Brienne of Tarth SPOUSE Jaime Lannister</td>\n",
       "      <td>[2190]</td>\n",
       "      <td>-0.004299</td>\n",
       "      <td>0.498925</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>Daenerys Targaryen ALLIED_WITH House Lannister...</td>\n",
       "      <td>[1937]</td>\n",
       "      <td>-0.008216</td>\n",
       "      <td>0.497946</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>18</th>\n",
       "      <td>Cersei Lannister PARENT_OF Brandon Stark</td>\n",
       "      <td>[2337]</td>\n",
       "      <td>-0.009620</td>\n",
       "      <td>0.497595</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>Brandon Stark ALLIED_WITH House Lannister of C...</td>\n",
       "      <td>[2257]</td>\n",
       "      <td>-0.020130</td>\n",
       "      <td>0.494968</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>19</th>\n",
       "      <td>Tywin Lannister PARENT_OF Jaime Lannister</td>\n",
       "      <td>[2748]</td>\n",
       "      <td>-0.025549</td>\n",
       "      <td>0.493613</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>Robert I Baratheon PARENT_OF Myrcella Baratheon</td>\n",
       "      <td>[3002]</td>\n",
       "      <td>-0.037298</td>\n",
       "      <td>0.490677</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>Daenerys Targaryen SPOUSE Craster</td>\n",
       "      <td>[2982]</td>\n",
       "      <td>-0.042962</td>\n",
       "      <td>0.489261</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>Daenerys Targaryen SPOUSE Jon Snow</td>\n",
       "      <td>[3311]</td>\n",
       "      <td>-0.054646</td>\n",
       "      <td>0.486342</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Tyrion Lannister SPOUSE Missandei</td>\n",
       "      <td>[3618]</td>\n",
       "      <td>-0.066496</td>\n",
       "      <td>0.483382</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                            statement    rank     score  \\\n",
       "12  House Hutcheson SWORN_TO House Tyrell of Highg...    [-1]  0.830148   \n",
       "9   Brandon Stark ALLIED_WITH House Stark of Winte...    [-1]  0.630217   \n",
       "6       House Stark of Winterfell IN_REGION The North     [7]  0.235329   \n",
       "8   House Tyrell of Highgarden IN_REGION Beyond th...   [206]  0.110351   \n",
       "3                    Sansa Stark SPOUSE Petyr Baelish   [499]  0.084068   \n",
       "7           House Stark of Winterfell IN_REGION Dorne   [637]  0.079129   \n",
       "13  Daenerys Targaryen ALLIED_WITH House Stark of ...   [688]  0.058003   \n",
       "15       Jaime Lannister PARENT_OF Myrcella Baratheon   [674]  0.055809   \n",
       "20                         Missandei SPOUSE Grey Worm   [650]  0.046343   \n",
       "2   King's Landing SEAT_OF House Lannister of Cast...  [1066]  0.032168   \n",
       "0             Jorah Mormont SPOUSE Daenerys Targaryen  [1645]  0.021946   \n",
       "11               Rhaegar Targaryen PARENT_OF Jon Snow  [1728]  0.008681   \n",
       "17      Cersei Lannister PARENT_OF Myrcella Baratheon  [1978]  0.006947   \n",
       "21            Brienne of Tarth SPOUSE Jaime Lannister  [2190] -0.004299   \n",
       "14  Daenerys Targaryen ALLIED_WITH House Lannister...  [1937] -0.008216   \n",
       "18           Cersei Lannister PARENT_OF Brandon Stark  [2337] -0.009620   \n",
       "10  Brandon Stark ALLIED_WITH House Lannister of C...  [2257] -0.020130   \n",
       "19          Tywin Lannister PARENT_OF Jaime Lannister  [2748] -0.025549   \n",
       "16    Robert I Baratheon PARENT_OF Myrcella Baratheon  [3002] -0.037298   \n",
       "5                   Daenerys Targaryen SPOUSE Craster  [2982] -0.042962   \n",
       "4                  Daenerys Targaryen SPOUSE Jon Snow  [3311] -0.054646   \n",
       "1                   Tyrion Lannister SPOUSE Missandei  [3618] -0.066496   \n",
       "\n",
       "        prob  \n",
       "12  0.696386  \n",
       "9   0.652539  \n",
       "6   0.558562  \n",
       "8   0.527560  \n",
       "3   0.521005  \n",
       "7   0.519772  \n",
       "13  0.514497  \n",
       "15  0.513949  \n",
       "20  0.511584  \n",
       "2   0.508041  \n",
       "0   0.505486  \n",
       "11  0.502170  \n",
       "17  0.501737  \n",
       "21  0.498925  \n",
       "14  0.497946  \n",
       "18  0.497595  \n",
       "10  0.494968  \n",
       "19  0.493613  \n",
       "16  0.490677  \n",
       "5   0.489261  \n",
       "4   0.486342  \n",
       "1   0.483382  "
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.DataFrame(list(zip([' '.join(x) for x in X_unseen], \n",
    "                      ranks_unseen, \n",
    "                      np.squeeze(scores),\n",
    "                      np.squeeze(probs))), \n",
    "             columns=['statement', 'rank', 'score', 'prob']).sort_values(\"score\", ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that the embeddings captured some truths about Westeros. For example, **House Stark is placed in the North rather than Dorne**. It also realises **Daenerys Targaryen has no relation with Craster**, **nor Tyrion with Missandei**. It captures random trivia, as **House Hutcheson is indeed in the Reach and sworn to the Tyrells**. On the other hand, some marriages that it predicts never really happened. These mistakes are understandable: those characters were indeed close and appeared together in many different circumstances. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 6. Visualizing Embeddings with Tensorboard projector\n",
    "\n",
    "The kind folks at Google have created [Tensorboard](https://www.tensorflow.org/tensorboard), which allows us to graph how our model is learning (or not :|), peer into the innards of neural networks, and [visualize high-dimensional embeddings in the browser](https://projector.tensorflow.org/).   \n",
    "\n",
    "Lets import the [`create_tensorboard_visualization`](http://docs.ampligraph.org/en/1.0.3/generated/ampligraph.utils.create_tensorboard_visualizations.html#ampligraph.utils.create_tensorboard_visualizations) function, which simplifies the creation of the files necessary for Tensorboard to display the embeddings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "from ampligraph.utils import create_tensorboard_visualizations"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And now we'll run the function with our model, specifying the output path:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "create_tensorboard_visualizations(model, 'GoT_embeddings')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If all went well, we should now have a number of files in the `AmpliGraph/tutorials/GoT_embeddings` directory:\n",
    "\n",
    "```\n",
    "GoT_embeddings/\n",
    "    ├── checkpoint\n",
    "    ├── embeddings_projector.tsv\n",
    "    ├── graph_embedding.ckpt.data-00000-of-00001\n",
    "    ├── graph_embedding.ckpt.index\n",
    "    ├── graph_embedding.ckpt.meta\n",
    "    ├── metadata.tsv\n",
    "    └── projector_config.pbtxt\n",
    "```\n",
    "\n",
    "To visualize the embeddings in Tensorboard, run the following from your command line inside `AmpliGraph/tutorials`:\n",
    "\n",
    "```bash\n",
    "tensorboard --logdir=./visualizations\n",
    "```\n",
    "    \n",
    ".. and once your browser opens up you should be able to see and explore your embeddings as below (PCA-reduced, two components):\n",
    "\n",
    "![](img/GoT_tensoboard.png)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "# The End\n",
    "\n",
    "You made it to the end! Well done!\n",
    "\n",
    "For more information please visit the [AmpliGraph GitHub](github.com/Accenture/AmpliGraph) (and remember to star the project!), or check out the [documentation](docs.ampligraph.org)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.10.6 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  },
  "vscode": {
   "interpreter": {
    "hash": "2e69f3670cdad0193847aaa0b77be56c05c951fcbdd384ff882dde0464f4de76"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
